package com.lyf.shop.dao.Impl;

import com.lyf.shop.dao.TypeDao;
import com.lyf.shop.entity.Type;
import com.lyf.shop.util.DataBaseUtil;
import com.lyf.shop.util.StrUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class TypeDaoImpl implements TypeDao {
    private QueryRunner qr = new QueryRunner();
    @Override
    public List<Type> getAll() throws SQLException{
        return qr.query(DataBaseUtil.getConnection(),
                "select * from type",new BeanListHandler<>(Type.class));
    }

    @Override
    public List<Type> getAllByKey(String tname) throws SQLException{
        String sql = "select * from type where 1=1";
        List<Object> param = new ArrayList<>();
        if(StrUtils.empty(tname)){
            sql+=" and tname like ?";
            param.add("%"+tname+"%");
        }
        return qr.query(DataBaseUtil.getConnection(),sql,new BeanListHandler<>(Type.class),param.toArray());
    }

    @Override
    public int addType(String tname, String tinfo) throws SQLException{
        return qr.update(DataBaseUtil.getConnection(),"insert into type values(default ,?,?)",tname,tinfo);
    }
}
